from rest_framework import serializers
from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password
from users.models import CaptchaReg
from django.utils import timezone

from utils.my_captcha import gen_captcha

User = get_user_model()


class UserUserNameLoginSerializer(serializers.Serializer):
    username = serializers.CharField(max_length=20)
    password = serializers.CharField(max_length=20)


class UserEmailLoginSerializer(serializers.Serializer):
    email = serializers.EmailField()
    password = serializers.CharField(max_length=20)


class UserInfoSerializer(serializers.ModelSerializer):

    # 这个步骤是专门给你用的,用于你去修改已经验证好的数据,大前提是你的数据通过验证了
    # 才去做定制化
    def validate(self, attrs):
        attrs['password'] = make_password(attrs['password'])
        email = attrs['email']
        captcha = attrs['captcha']
        validation_time = timezone.now() - timezone.timedelta(seconds=300)
        res = CaptchaReg.objects.filter(email=email, captcha=captcha, add_time__gte=validation_time).exists()
        if not res:
            raise serializers.ValidationError({'error': '验证码错误,或者失效'})
        del (attrs['captcha'])
        return super().validate(attrs)

    email = serializers.EmailField()
    # 只写
    captcha = serializers.CharField(max_length=6, min_length=6, write_only=True)

    class Meta:
        model = User
        fields = ("username", 'password', 'email', 'captcha')


class CaptchaRegSerializer(serializers.ModelSerializer):

    def validate(self, attrs):
        email = attrs['email']
        if User.objects.filter(email=email).exists():
            raise serializers.ValidationError({'error': '邮箱已经存在'})
        # 发送时间间隔的限制
        expire_time = timezone.now() - timezone.timedelta(seconds=120)
        if CaptchaReg.objects.filter(email=email, add_time__gt=expire_time).exists():
            raise serializers.ValidationError({'error': '请稍后再来发送验证码'})
        captcha = gen_captcha()
        attrs['captcha'] = captcha
        return super().validate(attrs)

    class Meta:
        model = CaptchaReg
        fields = ("email",)
